<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
                @close="hClose"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles" style="width: 100%">
              <el-table-column label="序号" type="index" :index="fetchIndex" width="50" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :page-size="pageParams.pagesize"
                layout="prev,pager,next"
                :total="total"
                @current-change="hCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        title="编辑弹层"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog=false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
      :visible.sync="showDialogAssign"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <assign-permission v-if="showDialogAssign" @close="showDialogAssign=false" />
    </el-dialog>
  </div>
</template>
<script>
import { getRoles, deleteRole, addRole, updateRole } from '@/api/settings'
import assignPermission from './assignPermission'

export default {
  components: {
    assignPermission
  },

  data() {
    return {
      pageParams: {
        page: 1, // 默认查询第一页
        pagesize: 2 // 默认每页两条
      },
      showDialogAssign: false, // 分配权限对话框
      activeName: 'first',
      roles: [],
      roleId: '',
      total: 0, // 总的数据条数
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      curPage: 1,
      isEdit: false // 是否是编辑

    }
  },
  // computed: {
  //   // 表格中最大的页码
  //   maxNum() {
  //     return Math.ceil(this.total / this.pageParams.pageSize)
  //   },
  //   // 最后一页是不是满的
  //   isLastPageFulled: function() {
  //     return this.total % this.pageParams.pageSize === 0
  //   }
  // },
  created() {
    this.loadRoles()
  },
  methods: {
    hAssign(id) {
      // 记下来id
      this.roleId = id
      this.showDialogAssign = true
    },
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log(res)
        this.roles = res.data.rows
        this.total = res.data.total

        this.curPage = this.pageParams.page
      } catch (err) {
        console.log(err)
      }
    },
    // 用户点击了页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.pageParams.page = curPage
      // 2. 重发请求
      this.loadRoles()
    },
    async doDel(id) {
      try {
        const res = await deleteRole(id)
        console.log(res)
        // 1. 提示
        this.$message.success('删除成功')
        if (this.roles.length === 0) {
          this.pageParams.page--
          if (this.pageParams.page < 1) {
            this.pageParams.page = 1
          }
        }
        // 2. 重新请求
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 用户点击了删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    async doAdd() {
      try {
        await addRole(this.roleForm)
        // console.log(res)
        // if (this.isLastPageFulled) {
        //   this.pageParams.page = this.maxNum + 1
        // } else {
        //   this.pageParams.page = this.maxNum
        // }
        this.pageParams.page = Math.ceil(++this.total / this.pageParams.pagesize)

        this.loadRoles()
        this.$message.success('添加成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('添加失败')
        console.log(err)
      }
    },
    // 用户点击了保存
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 用户点击了编辑
    hEdit(row) {
      // 1. 把当前的数据直接给表单
      this.roleForm = { ...row }

      // 2. 显示弹层
      this.showDialog = true
      // console.log(row)
    },
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res)

        this.loadRoles()
        this.$message.success('编辑成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('编辑失败')
        console.log(err)
      }
    },
    hClose() {
      console.log('close...............')
      // 重置表单
      this.roleForm = { // 表单数据项
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },
    // 自定义索引序号
    fetchIndex(index) {
      console.log(index) // 每一页的索引都是从0开始
      const page = this.pageParams.page
      const pagesize = this.pageParams.pagesize
      return (page - 1) * pagesize + index + 1
    }
  }
}
</script>
